(function() {
    tinymce.create('tinymce.plugins.WPAiWriter', {
        init: function(ed, url) {
            ed.addButton('wp_ai_writer', {
                title: 'AI写作助手',
                icon: 'ai-writer-icon',
                onclick: function() {
                    showAiWriterDialog(ed);
                }
            });
        }
    });

    function showAiWriterDialog(editor) {
        let dialog = jQuery('<div>', {
            id: 'ai-writer-dialog',
            title: 'AI写作助手'
        }).appendTo('body');

        // 创建对话框内容
        let content = `
            <div class="ai-writer-modes">
                <button class="continue-writing">续写模式</button>
                <button class="instruction-writing">指令写作</button>
            </div>
            <div class="ai-writer-instruction" style="display:none;">
                <textarea placeholder="请输入写作指令..."></textarea>
            </div>
            <div class="ai-writer-status"></div>
        `;

        dialog.html(content).dialog({
            width: 500,
            modal: true,
            buttons: {
                "生成": function() {
                    generateContent(editor, dialog);
                },
                "取消": function() {
                    jQuery(this).dialog('close');
                }
            }
        });
    }

    function generateContent(editor, dialog) {
        let content = editor.getContent();
        let instruction = dialog.find('.ai-writer-instruction textarea').val();
        
        dialog.find('.ai-writer-status').text('正在生成内容...');
        
        jQuery.ajax({
            url: wpAiWriter.ajax_url,
            type: 'POST',
            data: {
                action: 'wp_ai_writer_generate',
                content: content,
                instruction: instruction,
                nonce: wpAiWriter.nonce
            },
            success: function(response) {
                if (response.success) {
                    editor.setContent(response.data.content);
                    dialog.dialog('close');
                } else {
                    dialog.find('.ai-writer-status').text('生成失败：' + response.data.message);
                }
            }
        });
    }

    tinymce.PluginManager.add('wp_ai_writer', tinymce.plugins.WPAiWriter);
})(); 